package com.tian.service.impl.user;

import com.tian.common.enums.LoginTypeEnum;
import com.tian.common.exception.BusinessException;
import com.tian.common.exception.ValidException;
import com.tian.common.util.RedisConstantPre;
import com.tian.common.util.StringUtil;
import com.tian.dto.user.AuthLoginDto;
import com.tian.entity.ChargeUser;
import com.tian.mapper.ChargeUserMapper;
import com.tian.service.user.AbstractLoginService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * {@code @description:}  手机号+验证码
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-04-07 16:42
 * {@code @version:} 1.0
 */
@Slf4j
@Service
public class PhoneCodeLoginProcessorService extends AbstractLoginService {

    @Resource
    private RedissonClient redissonClient;
    @Resource
    ChargeUserMapper chargeUserMapper;

    @Override
    public int getLoginType() {
        return LoginTypeEnum.PHONE_CODE.getCode();
    }

    @Override
    public void validate(AuthLoginDto authLoginDto) {
        if (StringUtil.isBlank(authLoginDto.getPhone())) {
            throw new ValidException("手机号不能为空!");
        }
        if (StringUtil.isBlank(authLoginDto.getCode())) {
            throw new ValidException("验证码不能为空!");
        }
    }

    @Override
    public ChargeUser doProcessor(AuthLoginDto authLoginDto) {
        log.info("登录信息={}", authLoginDto);
        RBucket<String> bucket = redissonClient.getBucket(RedisConstantPre.SEND_CODE_PRE + authLoginDto.getPhone());
        String code = bucket.get();
        if (!code.equals(authLoginDto.getCode())) {
            throw new BusinessException("验证码有误");
        }
        log.info("begin PhoneCodeLoginProcessorService.doProcessor:" + authLoginDto);
        ChargeUser chargeUser = chargeUserMapper.selectByPhone(authLoginDto.getPhone());
        if (chargeUser == null) {
            throw new BusinessException("手机号未注册");
        }
        return chargeUser;
    }
}
